package com.renwei.db;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * Created by james on 2018/11/1.
 */
public class DynamicDataSourceHolder extends AbstractRoutingDataSource {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    @Override
    protected Object determineCurrentLookupKey() {
        String dataSource = getDataSource();
        System.out.println("----determineCurrentLookupKey-------:"+dataSource);
        return dataSource;
    }

    public static void setDataSource(String dataSource) {
        System.out.println("----setDataSource-------:" + dataSource);
        contextHolder.set(dataSource);
    }

    public static String getDataSource() {
        String dataSource = contextHolder.get();
        System.out.println("----getDataSource-------:"+dataSource);
        // 如果没有指定数据源，使用默认数据源
        if (null == dataSource) {
            DynamicDataSourceHolder.setDataSource("dataSource1");
        }
        return contextHolder.get();
    }

    /**
     * 清除数据源
     */
    public static void clearDataSource() {
        contextHolder.remove();
    }
}
